/*
 *  limitCharacts - v0.0.1
 *  Limits and trim the amount of characters added to any input/textarea tag
 *
 *  https://github.com/juanbrujo/limitCharacts
 *  Demo: http://juanbrujo.github.io/limitCharacts/
 *
 *  Author: Jorge Epuñan H. |  @csslab
 *  License: MIT
 *  ©2015
 */
 var charcount = require("../str/charcount");
 

module.exports = limitCharacts;

function limitCharacts(limitField, limitNum,isChar) {
    "use strict";
    function limiter(elem, countElem) {
        if (elem.value.length > limitNum) elem.value = elem.value.substring(0, limitNum); else {
			var elemval =  elem.value;
            var currentCount = limitNum - (isChar ? charcount(elemval) : elemval.length);
            valueCountElem(countElem, currentCount);
        }
    }
    function valueCountElem(elem, count) {
        elem instanceof HTMLInputElement && "text" === elem.type ? elem.value = count : elem.textContent = count;
    }

    limitField.length && [].forEach.call(limitField, function(elem) {
        var dataCount = elem.getAttribute("data-count"), countElem = document.querySelector(dataCount);
        valueCountElem(countElem, limitNum), 
		elem.addEventListener("input", function() {
            limiter(elem, countElem);
        });
    });
}